<template>
    <view class="container">
        <custom-nav-bar title="露营地预订与攻略平台" :show-back="false" />
        <view class="content">
            <!-- 1.0 搜索区域 -->
            <view class="search-section">
                <view class="search-box">
                    <text class="search-icon">🔍</text>
                    <input class="search-input" type="text" v-model="searchKey" placeholder="搜索攻略" @input="onSearch" />
                </view>
            </view> <!-- 2.0 分类选项 -->
            <view class="category-section">
                <view class="category-item" v-for="item in categories" :key="item.id"
                    :class="{ 'active': Number(currentCategory) === Number(item.id) }" @tap="switchCategory(item)">
                    <text>{{ item.name }}</text>
                </view>
            </view>

            <!-- 3.0 攻略列表 -->
            <scroll-view class="guide-section" scroll-y>
                <view class="guide-list">
                    <view class="guide-item" v-for="guide in filteredGuides" :key="guide.id"
                        @tap="onGuideDetail(guide)">
                        <image :src="guide.image" mode="aspectFill" class="guide-image" />
                        <view class="guide-info">
                            <text class="guide-title">{{ guide.title }}</text>
                            <text class="guide-desc">{{ guide.description }}</text>
                            <view class="guide-meta">
                                <text class="guide-date">{{ guide.date }}</text>
                                <text class="guide-views">{{ guide.views }}阅读</text>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { guideApi } from '@/api/index'
import CustomNavBar from '@/components/custom-nav-bar/custom-nav-bar.vue'

// 响应式数据
const searchKey = ref('')
const currentCategory = ref(0)
const categories = ref([])
const guideList = ref([])

// 获取攻略分类数据
const fetchCategories = async () => {
    try {
        const res = await guideApi.getGuideCategories()
        if (res.data) {
            // 确保数据是数组格式
            categories.value = Array.isArray(res.data) ? res.data : []
            // 添加默认分类
            categories.value.unshift({ id: 0, name: '全部' })
            // 初始化当前分类为第一个分类
            currentCategory.value = categories.value[0].id
            console.log('分类数据:', categories.value)
        } else {
            console.warn('获取分类数据格式不正确:', res.data)
            uni.showToast({
                title: '获取分类数据格式不正确',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取分类失败:', error)
        uni.showToast({
            title: '获取分类失败',
            icon: 'none'
        })
    }
}

// 获取攻略列表数据
const fetchGuides = async () => {
    try {
        const res = await guideApi.getGuideList()
        if (Array.isArray(res.data)) {
            guideList.value = res.data.map(guide => ({
                id: guide.id,
                title: guide.title,
                description: guide.description,
                content: guide.content,
                image: guide.coverUrl,
                coverUrl: guide.coverUrl,
                categoryId: guide.categoryId,
                views: guide.views,
                status: guide.status,
                createdAt: guide.createdAt,
                date: new Date(guide.createdAt).toLocaleDateString()
            }))
        }
    } catch (error) {
        console.error('获取攻略列表失败:', error)
        uni.showToast({
            title: '获取攻略列表失败',
            icon: 'none'
        })
    }
}

// 根据搜索关键字和分类筛选攻略
const filteredGuides = computed(() => {
    return guideList.value.filter(guide => {
        // 分类过滤 - 确保类型一致进行比较
        console.log('当前分类:', currentCategory.value, '攻略分类:', guide)
        const categoryMatch = Number(currentCategory.value) === 0 || Number(guide.categoryId) === Number(currentCategory.value)

        // 搜索关键字过滤
        const searchStr = searchKey.value.toLowerCase()
        const titleMatch = guide.title.toLowerCase().includes(searchStr)
        const descMatch = guide.description.toLowerCase().includes(searchStr)

        // 同时满足分类和搜索条件
        return categoryMatch && (searchStr === '' || titleMatch || descMatch)
    })
})

// 切换分类
const switchCategory = (category) => {
    currentCategory.value = category.id
    // 不需要重新请求数据，computed 属性会自动根据 currentCategory 过滤
}

// 搜索框输入事件
const onSearch = () => {
    // 通过计算属性自动过滤，无需额外处理
}

// 跳转到攻略详情
const onGuideDetail = (guide) => {
    const params = {
        id: guide.id,
        coverUrl: guide.coverUrl,     // 修正字段名：coverUrl 而不是 icoverUrl
        views: guide.views,
        title: guide.title,
        description: guide.description,
        createdAt: guide.createdAt,
        content: guide.content,
        categoryId: guide.categoryId // 添加分类ID用于获取相关营地
    }
    // 构建查询字符串
    const queryItems = []
    for (const [key, value] of Object.entries(params)) {
        if (value !== null && value !== undefined && value !== '') {
            queryItems.push(`${key}=${encodeURIComponent(value)}`)
        }
    }
    const query = queryItems.join('&')

    uni.navigateTo({
        url: `/pages/guide-detail/index?${query}`
    })
}

// 页面加载
onMounted(() => {
    fetchCategories()
    fetchGuides()

})
</script>

<style>
.container {
    background: #f5f5f5;
}

/* 搜索区域样式 */
.search-section {
    padding: 20rpx;
    background: #fff;
}

.search-box {
    display: flex;
    align-items: center;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
}

.search-icon {
    font-size: 28rpx;
    color: #999;
    margin-right: 10rpx;
}

.search-input {
    flex: 1;
    height: 100%;
    font-size: 28rpx;
}

/* 分类样式 */
.category-section {
    display: flex;
    background: #fff;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;
}

.category-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 0;
    position: relative;
}

.category-item.active {
    color: #409eff;
    font-weight: bold;
}

.category-item.active::after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background: #409eff;
    border-radius: 2rpx;
}

/* 攻略列表样式 */
.guide-section {
    height: calc(100vh - 200rpx);
}

.guide-list {
    padding: 20rpx;
}

.guide-item {
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 12rpx;
    overflow: hidden;
}

.guide-image {
    width: 100%;
    height: 300rpx;
}

.guide-info {
    padding: 20rpx;
}

.guide-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.guide-desc {
    font-size: 26rpx;
    color: #666;
    margin: 10rpx 0;
}

.guide-meta {
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
}

.content {
    margin-top: 100rpx;
}
</style>